#define TRACE
using System;
using System.Collections;
using System.Data;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Security;
using System.Text.RegularExpressions;
using System.Web;
using Microsoft.ApplicationBlocks.ExceptionManagement;
using Dimok.Data;
using Dimok.Exceptions;
using ConfigWS = Dimok.Config.imaging.WS;
using Tiffer;
using Dimok;
using Dimok.Data.Database;
using Dimok.User;

////////////////////////////////////////////////////////////////////////////////////////////////////
// namespace: Dimok.Images
//
// summary:	.
////////////////////////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////////////////////////
// namespace: Dimok.Images
//
// summary:	.
////////////////////////////////////////////////////////////////////////////////////////////////////

namespace Dimok.Images
{
	////////////////////////////////////////////////////////////////////////////////////////////////////
	/// <summary>	Build HTML List from images on disk (imagePath in config file) </summary>
	///
	/// <remarks>	Dimon, 12/21/2010. </remarks>
	////////////////////////////////////////////////////////////////////////////////////////////////////

	public class List{

		////////////////////////////////////////////////////////////////////////////////////////////////////
		/// <summary>	Makes a list file name. </summary>
		///
		/// <remarks>	Dimon, 12/21/2010. </remarks>
		///
		/// <exception cref="Exception">	Thrown when exception. </exception>
		///
		/// <param name="fileInfo">					Information describing the file. </param>
		/// <param name="longNameTemplate">	The long name template. </param>
		////////////////////////////////////////////////////////////////////////////////////////////////////

		private static void MakeListFileName(FileInfo fileInfo,string longNameTemplate){
			string newFile = "";
			if( Dimok.Common.IsNumeric(Path.GetFileNameWithoutExtension(fileInfo.Name)) ){
				newFile = Path.Combine(fileInfo.DirectoryName,fileInfo.Name.Replace(".","_."));
				try{fileInfo.MoveTo(FileManager.GetSureFileName(newFile,"00"));
				}catch(Exception exc){ throw new Exception("Move to:"+newFile,exc); }
			}
			if( !Path.HasExtension(fileInfo.Name) )
				try{
					newFile = FileManager.GetSureFileName(fileInfo.FullName+"."+Enums.GetExtention(fileInfo.FullName),"00");
					fileInfo.MoveTo(newFile);
				}catch(Exception exc){ throw new Exception("Move to:"+newFile,exc); }
			if( longNameTemplate == null || longNameTemplate == "" || !Regex.IsMatch(fileInfo.Name,longNameTemplate,RegexOptions.IgnoreCase | RegexOptions.Compiled) )return;
			//throw new Exception("FileName:"+fileInfo.Name+",template:["+longNameTemplate+"]");
			string fileName = fileInfo.LastWriteTime.ToString("dd_HHmmss")+fileInfo.Extension;
			fileInfo.MoveTo(Dimok.FileManager.GetSureFileName(Path.Combine(fileInfo.DirectoryName,fileName)));
		}
		private const string PAGES_TABLE = @"
<TABLE id='divPages' datasrc='#xmlPages~~UNUQUE~~' cellpadding='0' cellspacing='0' onreadystatechange='divFiles.showPagesTable(this)' style='display:none'>
		<TR><TD><SPAN id='divPage' datafld='PageNumber' class='Page'></SPAN></TD></TR>
</TABLE>";

		////////////////////////////////////////////////////////////////////////////////////////////////////
		/// <summary>	Files list. </summary>
		///
		/// <remarks>	Dimon, 12/21/2010. </remarks>
		///
		/// <param name="menuID">	Identifier for the menu. </param>
		///
		/// <returns>	. </returns>
		////////////////////////////////////////////////////////////////////////////////////////////////////

		public static DataSet FilesList(int menuID){
			UserObject uox = new UserObject();
			string sql = SQLHelperEx.ExecuteScalarEx(uox.db,"SELECT OnClick FROM t_Menu WHERE MenuID=@MID",menuID)+"";
			sql = Regex.Replace(sql,@"^SELECT\s+.+\s+FROM\s+","SELECT ApplicantID AS FileName,0 Size,'' AS Date,'/Images/Plus_big.gif' AS Image FROM ",RegexOptions.IgnoreCase);
			StringList slWhere = new StringList();
			string group = UserObject.GetQueryParam("Group");
			if( group != "" )slWhere.Add("[Group]="+int.Parse(group));
			string approved = UserObject.GetQueryParam("Approved");
			if( approved != "" )slWhere.Add("[Approved]="+int.Parse(approved));
			if(slWhere.Count > 0 )sql += " WHERE "+slWhere.Join(" AND ");
			return SQLHelperEx.ExecuteDatasetEx(uox.db,sql.Replace("~menuid~","@MID"),menuID);
		}

		////////////////////////////////////////////////////////////////////////////////////////////////////
		/// <summary>	Files list. </summary>
		///
		/// <remarks>	Dimon, 12/21/2010. </remarks>
		///
		/// <returns>	. </returns>
		////////////////////////////////////////////////////////////////////////////////////////////////////

		public static DataSet FilesList(){return FilesList(ConfigWS.ImagePath,"");}

		////////////////////////////////////////////////////////////////////////////////////////////////////
		/// <summary>	Files list. </summary>
		///
		/// <remarks>	Dimon, 12/21/2010. </remarks>
		///
		/// <exception cref="Exception">	Thrown when exception. </exception>
		///
		/// <param name="path">							Full pathname of the file. </param>
		/// <param name="longNameTemplate">	The long name template. </param>
		///
		/// <returns>	. </returns>
		////////////////////////////////////////////////////////////////////////////////////////////////////

		public static DataSet FilesList(string path,string longNameTemplate){
			try{
				DirectoryInfo di = new DirectoryInfo(path);
				string[] Icons = new string[]{"kodak.gif","","PDF.gif","blank16x16.gif"};
				NumberFormatInfo nfi = new NumberFormatInfo();
				nfi.NumberDecimalDigits = 0;
				ImageFileDS.FileDataTable dtFiles = new ImageFileDS().File;
				foreach( FileInfo fi in di.GetFiles() ){
					MakeListFileName(fi,longNameTemplate);
					PageTypes pageType = PageTypes.UNKNOWN;
					int pageCount = -1;
					try { pageType = Enums.GetPageType(fi.FullName); 
					} catch (EmptyFileException exc) { pageCount = 0; exc.Data["File"] = fi.FullName; ASPException.Publish(exc);
					} catch (PageTypeException exc) { pageCount = 0; exc.Data["File"] = fi.FullName; ASPException.Publish(exc); }
					long fileLength = new FileInfo(fi.FullName).Length;
					try {
						pageCount = fileLength == 0 || pageCount >= 0 ? pageCount : ImageFiles.PageCount(fi.FullName);
					} catch (Exception exc) {
						ExceptionManager.Publish(exc);
						//continue;
					}
					dtFiles.AddFileRow(Path.GetFileNameWithoutExtension(fi.Name), fi.Name, fi.Length.ToString("N", nfi),
						fi.CreationTime.ToString("g"), fi.CreationTime.ToString("s"),
						pageCount+"", "/Images/Buttons/"+Icons[pageType==PageTypes.UNKNOWN?3:(int)pageType],
						"<XML id='xmlPages"+fi.GetHashCode()+"'></XML>",
						PAGES_TABLE.Replace("~~UNUQUE~~",fi.GetHashCode()+""),0+"");
				};
				dtFiles.DefaultView.Sort = "dateSort";
				ImageFileDS.FileDataTable dtSorted = (ImageFileDS.FileDataTable)dtFiles.Clone();
				foreach(ImageFileDS.FileRow row in dtFiles.Select("","DateSort ASC") ){
					dtSorted.Rows.Add(row.ItemArray);
				}
				DataSet ds = dtFiles.DataSet;
				ds.Tables.Remove(dtFiles);
				ds.Tables.Add(dtSorted);
				if( dtSorted.Rows.Count == 0 ) dtSorted.AddFileRow("No Files","0","","","",0+"",Icons[3],"","",0+"");
				return dtSorted.DataSet;
			}catch( SecurityException exp ){
				throw new Exception("\nCan't access "+path+".\n",exp);
			}catch( IOException exp ){
				throw new Exception("\nFile "+path+" not found.\n",exp);
			}
		}
	}
}
